//index.js
//获取应用实例
const app = getApp()
var wxCharts = require('../../charts/wxcharts.js');

let SCORE = []

for (let i = 0; i < 32; i++) {
    SCORE.push({
        id: '',
        name: '',
        img: '',
        level: 0,
        index: i
    })
}


Page({
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        wlad: {
            adData: {},
            ad: {
                banner: ["banner"]
            }
        },
        userInfo: {},
        curScore: {},
        hasUserInfo: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        maskshow: false,
        noScroe: true,
        imglist: [],
        ishasEffect: false,
        hasEffect:[],
        noLength: true,
        roleloading: false,
        money:0,
        allRace: {
            obj: []
        },
        picloading: false,
        posterConfig: {
            width: 375,
            height: 900,
            backgroundColor: '#ffffff',
            debug: true
        }
    },

    onLoad: function() {
        if (app.globalData.userInfo) {
            this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
            })
        } else if (this.data.canIUse) {
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.userInfoReadyCallback = res => {
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
                success: res => {
                    app.globalData.userInfo = res.userInfo
                    this.setData({
                        userInfo: res.userInfo,
                        hasUserInfo: true
                    })
                }
            })
        }
        this.setData({
            scoreData: SCORE
        })
        this.getOpenid()
        this.getRole()
        this.getEffect()
    },
    onShow() {
        let falg = true;
        if (this.data.allRace.obj.length > 0) {
            falg = false
        }
        this.setData({
            noScroe: falg
        })
    },
    changeMoney(arr){
        let temp = 0;
        
        for(let i in arr){
            if (arr[i].level == 1){
                temp = temp + arr[i].price
            } else if (arr[i].level == 2){
                temp = temp + arr[i].price * 3
            } else if (arr[i].level == 3){
                temp = temp + arr[i].price * 9
            }
        }

        this.setData({
            money: temp
        })
    },
    getOpenid() {
        wx.cloud.callFunction({
            name: 'login',
            success: res => {
                console.log(res)
                app.globalData.openid = res.result.openid;
            },
            fail: err => {
                wx.showToast({
                    icon: 'none',
                    title: '调用失败',
                })
                console.error('[云函数] [login] 调用失败：', err)
            }
        })
    },
    draw(id, data) {
        if (data.obj.length <= 0) {
            this.setData({
                noScroe: true
            })
            return false
        } else {
            this.setData({
                noScroe: false
            })
        }
        new wxCharts({
            canvasId: id,
            type: 'column',
            categories: data.obj,
            series: [{
                data: data.number
            }],
            legend: false,
            yAxis: {
                disabled: true,
                min: 0,
                disableGrid: true,
                gridColor: '#f1f1f1'
            },
            xAxis: {
                gridColor: '#f1f1f1',
            },
            width: 325,
            height: 100
        });
    },
    drawCombat(data) {
        new wxCharts({
            canvasId: 'combat-canvas',
            type: 'radar',
            categories: ['控制', '血量', '远程输出', 'AOE', '近战输出'],
            series: [{
                data: data
            }],
            width: 320,
            height: 180,
            legend: false,
            extra: {
                radar: {
                    gridColor: '#f1f1f1',
                    max: 200
                }
            }
        });
    },
    getUserInfo: function(e) {
        console.log(e)
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    getTempFileURL: function(list) {
        var that = this;
        if (!list) {
            return false
        }
        if (list.length >= 50) {
            wx.cloud.getTempFileURL({
                fileList: list.slice(0, 50),
                success: ress => {
                    wx.cloud.getTempFileURL({
                        fileList: list.slice(50, 100),
                        success: res => {
                            that.setData({
                                urlList: ress.fileList.concat(res.fileList),
                                roleloading: false
                            })

                        },
                        fail: console.error
                    })

                },
                fail: console.error
            })
        } else {
            wx.cloud.getTempFileURL({
                fileList: list,
                success: res => {
                    that.setData({
                        urlList: res.fileList,
                        roleloading: false
                    })
                },
                fail: console.error
            })
        }
    },
    getRole() {
        this.setData({
            roleloading: true
        })
        wx.cloud.callFunction({
            name: 'getRole',
            success: res => {
                console.log(res)
                this.setData({
                    role: res.result.data.sort((a, b) => {
                        return a.price - b.price
                    })
                })
                let imglist = []
                for (let i in this.data.role) {
                    imglist.push(this.data.role[i].img)
                }
                this.setData({
                    imglist: imglist
                })
                this.getTempFileURL(imglist)
            },
            fail: err => {
                wx.showToast({
                    icon: 'none',
                    title: '调用失败',
                })
                console.error('[云函数] [login] 调用失败：', err)
            }
        })
    },
    getEffect() {
        wx.cloud.callFunction({
            name: 'getEffect',
            success: res => {
                console.log(res)
                this.setData({
                    effect: res.result.data
                })
            },
            fail: err => {
                wx.showToast({
                    icon: 'none',
                    title: '调用失败',
                })
                console.error('[云函数] [login] 调用失败：', err)
            }
        })
    },
    showmask(e) {
        this.setData({
            maskshow: true,
            curScore: this.data.scoreData[e.currentTarget.dataset.index]
        })
    },
    close() {
        this.setData({
            maskshow: false
        })
    },
    onShareAppMessage() {
        return {
            title: '自走棋，皇后局都用什么阵容',
            imageUrl: '../../images/share_bg.png'
        }
    },
    addscroe(e) {
        let arr = this.data.scoreData;

        if (arr.filter((ele) => {
                return ele.id != ''
            }).length >= 10) {
            wx.showToast({
                icon: 'none',
                title: '最多10个棋子',
            })
            return false
        }

        arr[this.data.curScore.index] = {
            id: e.currentTarget.dataset.id,
            level: e.currentTarget.dataset.level,
            name: this.data.role[e.currentTarget.dataset.index].short,
            img: this.data.urlList[e.currentTarget.dataset.index].tempFileURL,
            index: this.data.curScore.index,
            race: this.data.role[e.currentTarget.dataset.index].race,
            profession: this.data.role[e.currentTarget.dataset.index].profession,
            price: this.data.role[e.currentTarget.dataset.index].price,
            aoe: this.data.role[e.currentTarget.dataset.index].aoe,
            control: this.data.role[e.currentTarget.dataset.index].control,
            attDistance: this.data.role[e.currentTarget.dataset.index].attDistance,
            attribute: this.data.role[e.currentTarget.dataset.index].attribute,
            cloudImg: this.data.imglist[e.currentTarget.dataset.index],
        }
        this.setData({
            scoreData: arr
        })
        this.close()
        this.statisticsRace()
    },
    clearCurscore(e) {
        let arr = this.data.scoreData;
        arr[e.currentTarget.dataset.index] = {
            id: '',
            level: 0,
            name: '',
            img: '',
            index: e.currentTarget.dataset.index
        }
        this.setData({
            curScore: {
                index: e.currentTarget.dataset.index,
                id: '',
                level: 0,
                img: '',
                name: ''
            },
            scoreData: arr
        })
        this.statisticsRace()
    },
    clearAll() {
        let arr = []
        for (let i = 0; i < 32; i++) {
            arr.push({
                id: '',
                name: '',
                img: '',
                level: 0,
                index: i
            })
        }
        this.setData({
            scoreData: arr,
            noScroe: true,
            money:0
        })

    },
    //数组对象去重
    arrayUnique(arr, name) {
        var hash = {};
        return arr.reduce(function(item, next) {
            hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
            return item;
        }, [])
    },
    //数组统计
    arrayStatistics(arr) {
        let obj = [];
        let number = [];
        for (let i = 0; i < arr.length; i++) {
            if (obj.indexOf(arr[i]) >= 0) {
                number[obj.indexOf(arr[i])] = number[obj.indexOf(arr[i])] + 1
            } else {
                obj.push(arr[i])
                number.push(1)
            }
        }
        return {
            obj: obj,
            number: number
        }
    },
    statisticsRace() {
        let arr = this.data.scoreData;
        let hasArr = arr.filter((ele, index, self) => {
            return (ele.id != '')
        })

        this.changeMoney(hasArr)

        let sginArr = this.arrayUnique(hasArr, 'id');
        let allRace = []
        for (let i in sginArr) {
            if (sginArr[i].race.indexOf('-') > 0) {
                let arr = sginArr[i].race.split('-')
                for (let j in arr)(
                    allRace.push(arr[j])
                )
            } else {
                allRace.push(sginArr[i].race)
            }
        }
        let allProfession = []
        for (let i in sginArr) {
            allProfession.push(sginArr[i].profession)
        }
        let data1 = this.arrayStatistics(allRace);
        let data2 = this.arrayStatistics(allProfession);
        this.setData({
            allRace: data1,
            allProfession: data2
        })
        this.draw('race-canvas', data1)
        this.draw('occupation-canvas', data2)
        this.createEffect()

        //画雷达图
        if (hasArr.length <= 0) {
            this.setData({
                noScroe: true
            })
            return false
        } else {
            if (hasArr.length <= 4) {
                this.setData({
                    noScroe: false,
                    noLength: true
                })
                return false
            } else {
                this.setData({
                    noScroe: false,
                    noLength: false
                })
                let redaerData = [0, 0, 0, 0, 0]
                for (let i in hasArr) {
                    redaerData[0] = redaerData[0] + (hasArr[i].control == 0 ? 0 :hasArr[i].control + ((hasArr[i].level - 1) * 5));
                    redaerData[3] = redaerData[3] + (hasArr[i].aoe == 0 ? 0 :hasArr[i].aoe + ((hasArr[i].level - 1) * 5));
                    let temp = parseInt(hasArr[i].attribute[(hasArr[i].level - 1)].armor);
                    let xishu = temp == 0 ? 1 :  1 - parseFloat((temp * 0.06) / (1 + temp * 0.06)).toFixed(1)
                    redaerData[1] = redaerData[1] + parseInt((hasArr[i].attribute[(hasArr[i].level - 1)].blood / xishu) * 0.006);
                    if (hasArr[i].attDistance == 0){
                        redaerData[4] = redaerData[4] + parseInt(((parseInt(hasArr[i].attribute[(hasArr[i].level - 1)].max_attack) + parseInt(hasArr[i].attribute[(hasArr[i].level - 1)].min_attack)) / 2) / hasArr[i].attribute[(hasArr[i].level - 1)].aspeed);
                    }
                    if (hasArr[i].attDistance == 1) {
                        redaerData[2] = redaerData[2] + parseInt(((parseInt(hasArr[i].attribute[(hasArr[i].level - 1)].max_attack) + parseInt(hasArr[i].attribute[(hasArr[i].level - 1)].min_attack)) / 2) / hasArr[i].attribute[(hasArr[i].level - 1)].aspeed);
                    }
                }
                console.log(redaerData)
                this.drawCombat(redaerData)
            }
        }
    },
    createEffect() {
        let raceDataArr = [];
        let allRace = this.data.allRace;
        for (let i in allRace.obj) {
            let tempObj = this.data.effect.filter((ele) => {
                return ele.name == allRace.obj[i]
            });
            if (tempObj.length > 0) {
                tempObj = tempObj[0];
                for (let j in tempObj.effect) {
                   if (allRace.number[i] >= parseInt(j)) {
                       raceDataArr.push(tempObj.name + '（' + j + '）' + tempObj.effect[j])
                   }
                }
            }
        }

        let professionDataArr = [];
        let allProfession = this.data.allProfession;
        for (let i in allProfession.obj) {
            let tempObj = this.data.effect.filter((ele) => {
                return ele.name == allProfession.obj[i]
            });
            if (tempObj.length > 0) {
                tempObj = tempObj[0];
                for (let j in tempObj.effect) {
                    if (allProfession.number[i] >= parseInt(j)) {
                        professionDataArr.push(tempObj.name + '（' + j + '）' + tempObj.effect[j])
                    }
                }
            }
        }

        let finData = raceDataArr.concat(professionDataArr);
    
        this.setData({
            hasEffect: finData,
            ishasEffect: finData.length <= 0 ? true : false
        })
        if (!this.searchArrItem('恶魔猎手（2）')){
            let f = false;
            if (this.searchArrItem('恶魔（1）')){
                let eNum = this.data.allRace.number[this.data.allRace.obj.indexOf('恶魔')];
                if(eNum >= 2){
                    f = true;
                }
            }
            if(f){
                this.removeArrItem('恶魔（1）');
            }
        }

        if (this.searchArrItem('精灵') || this.searchArrItem('人类') || this.searchArrItem('兽人') || this.searchArrItem('龙') || this.searchArrItem('矮人') || this.searchArrItem('食人魔') || this.searchArrItem('恶魔（1）') || this.searchArrItem('地精') || this.searchArrItem('巨魔') || this.searchArrItem('亡灵') || this.searchArrItem('元素') || this.searchArrItem('娜迦') || this.searchArrItem('萨特')){
            this.removeArrItem('神');
            this.removeArrItem('神');
        }

        this.setData({
            ishasEffect: this.data.hasEffect.length <= 0 ? true : false
        })
    },
    searchArrItem(name){
        let arr = this.data.hasEffect;
        let flag = false;
        for (let i in arr) {
            if (arr[i].indexOf(name) >= 0) {
                flag = true
            }
        }
        return flag
    },
    removeArrItem(name){
        let arr = this.data.hasEffect;
        for (let i in arr){
            if (arr[i].indexOf(name) >= 0){
                arr.splice(i,1);
                this.setData({
                    hasEffect: arr,
                })
            }
        }
    },
    toPicture() {
        if (this.data.noScroe) {
            wx.showToast({
                icon: 'none',
                title: '请填入棋子'
            })
            return false
        }
        this.setData({
            picloading: true
        })
        app.globalData.money = this.data.money;
        app.globalData.effectData = this.data.hasEffect;
        app.globalData.detailsData = this.data.scoreData;
        wx.canvasToTempFilePath({
            canvasId: 'race-canvas',
            success: (res) => {
                wx.canvasToTempFilePath({
                    canvasId: 'occupation-canvas',
                    success: (ress) => {
                        if (!this.data.noLength) {
                            wx.canvasToTempFilePath({
                                canvasId: 'combat-canvas',
                                success: (resss) => {
                                    this.setData({
                                        picloading: false
                                    })
                                    wx.reportAnalytics('save_picture_index', {
                                        number: 1,
                                    });
                                    wx.navigateTo({
                                        url: `../../pages/picture/picture?pic1=${res.tempFilePath}&pic2=${ress.tempFilePath}&pic3=${resss.tempFilePath}`,
                                    })
                                },
                                fail: () => {
                                    this.setData({
                                        picloading: false
                                    })
                                }
                            })
                        } else {
                            wx.reportAnalytics('save_picture_index', {
                                number: 1,
                            });
                            this.setData({
                                picloading: false
                            })
                            wx.navigateTo({
                                url: `../../pages/picture/picture?pic1=${res.tempFilePath}&pic2=${ress.tempFilePath}`,
                            })
                        }
                    },
                    fail: () => {
                        this.setData({
                            picloading: false
                        })
                    }
                })
            },
            fail: () => {
                this.setData({
                    picloading: false
                })
            }
        })
    },
    tofix(){
        wx.navigateTo({
            url: '../../pages/fixData/fix',
        })
    },
    showtip(){
        wx.showToast({
            icon:'none',
            title: '点击棋谱中格子',
        })
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 300
        })
    }
})